﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fis.Web.Rules.Service
{
    public class UserRule : Agile.Engine.Data.DataRule
    {
        string DataTableName = "TUSER";

        public override void ExecuteNonTrans()
        {
            var action = Paramater["action"].ToString();
            System.Data.DataTable data = null;
            switch (action)
            {
                case "schema":
                    data = Model.QueryTable(DataTableName, "1=2");
                    data.Rows.Add(data.NewRow());
                    break;
                case "save":
                    data = Save(int.Parse(Paramater["state"].ToString()));
                    break;
                case "load":
                    data = Model.QueryTable(DataTableName, string.Format("SID='{0}'", Paramater["SID"]));
                    break;
                case "delete":
                    Model.Delete(DataTableName, string.Format("SID='{0}'", Paramater["SID"]));
                    break;
                case "query":
                    data = Model.QueryTable(DataTableName, Paramater["filter"].ToString());
                    if (data.Rows.Count == 0)
                        Message = "查询结果为空";
                    break;
            }

            Result["data"] = (data != null && data.Rows.Count > 0) ? Agile.Engine.Utils.ZipUtils.ZipDataTable(data) : null;
        }

        System.Data.DataTable Save(int state)
        {
            var data = Agile.Engine.Utils.ZipUtils.UnZipDataTable(Paramater["data"].ToString());
            var da = new Agile.Engine.Data.DataAccess() { Context = Model.DataContext, TableName = DataTableName };
            switch (state)
            {
                case 1://addnew
                    data.Rows[0]["SID"] = Guid.NewGuid().ToString();
                    data.Rows[0]["SINDEXDATE"] = DateTime.Now;
                    da.AddNew(data.Rows[0]);
                    break;
                case 2://modify
                    data.Rows[0]["SINDEXDATE"] = DateTime.Now;
                    da.Update(data.Rows[0]);
                    break;
            }

            return data;
        }
    }
}
